package BinaryTree;

import java.util.*;

/**
 * Created with Intellij JDEA
 * Description:
 * User:
 * Date:2022-03-22
 * Time:16:10
 */
public class BinaryTree {

    static class TreeNode {
        public char val;
        public TreeNode left;
        public TreeNode right;

        /**
         * 构造方法，构造一个节点
         *
         * @param val
         */
        public TreeNode(char val) {
            this.val = val;
        }
    }

    public TreeNode creteTree() {
        TreeNode A = new TreeNode('A');
        TreeNode B = new TreeNode('B');
        TreeNode C = new TreeNode('C');
        TreeNode D = new TreeNode('D');
        TreeNode E = new TreeNode('E');
        TreeNode F = new TreeNode('F');
        TreeNode G = new TreeNode('G');
        TreeNode H = new TreeNode('H');

        A.left = B;
        A.right = C;
        B.left = D;
        B.right = E;
        //E.right = H;
        C.left = F;
        C.right = G;
        return A;//根节点
    }


    // 前序遍历
    void preOrder(TreeNode root) {
        if (root == null) {
            return;
        }
        System.out.println(root.val + " ");
        preOrder(root.left);
        preOrder(root.right);
    }

    //子树列思路
    public List<Integer> preorderTraversal3(TreeNode root) {
        List<Integer> list = new ArrayList<>();
        if (root == null) {
            return list;
        }
        list.add((int) root.val);
        List<Integer> leftList = preorderTraversal3(root.left);
        list.addAll(leftList);
        List<Integer> rightList = preorderTraversal3(root.right);
        list.addAll(rightList);
        return list;
    }

    public List<Integer> preorderTraversal(TreeNode root) {
        List<Integer> list = new ArrayList<>();
        if (root == null) {
            return list;
        }
        return preorderTraversalChild(root, list);
    }

    private List<Integer> preorderTraversalChild(TreeNode root, List<Integer> list) {
        if (root == null) {
            return null;
        }
        list.add((int) root.val);
        preorderTraversalChild(root.left, list);
        preorderTraversalChild(root.right, list);
        return list;
    }

    // 中序遍历
    void inOrder(TreeNode root) {
        if (root == null) {
            return;
        }
        preOrder(root.left);
        System.out.println(root.val + " ");
        preOrder(root.right);
    }

    // 后序遍历
    void postOrde(TreeNode root) {
        if (root == null) {
            return;
        }
        preOrder(root.left);
        preOrder(root.right);
        System.out.println(root.val + " ");
    }

    // 获取树中节点的个数
    public static int count = 0;

    public void size(TreeNode root) {
        if (root == null) {
            return;
        }
        count++;
        size(root.left);
        size(root.right);
    }

    // 子问题思路-求节点个数
    int size2(TreeNode root) {
        if (root == null) {
            return 0;
        }
        return size2(root.left) + size2(root.right) + 1;
    }

    // 获取叶子节点的个数
    public static int count2 = 0;

    void getLeafNodeCount1(TreeNode root) {
        if (root == null) {
            return;
        }
        if (root.left == null && root.right == null) {
            count2++;
        }
        getLeafNodeCount1(root.left);
        getLeafNodeCount1(root.right);
    }

    // 子问题思路-求叶子结点个数
    int getLeafNodeCount2(TreeNode root) {
        if (root == null) {
            return 0;
        }
        if (root.left == null && root.right == null) {
            return 1;
        }
        return getLeafNodeCount2(root.left) + getLeafNodeCount2(root.right);
    }

    // 获取第K层节点的个数
    int getKLevelNodeCount(TreeNode root, int k) {
        if (root == null) {
            return 0;
        }
        if (k == 1) {
            return 1;
        }
        return getKLevelNodeCount(root.left, k - 1) + getKLevelNodeCount(root.right, k - 1);
    }
    // 获取二叉树的高度

    /**
     * O(N*N)
     *
     * @param root
     * @return
     */
    int getHeight(TreeNode root) {
        if (root == null) {
            return 0;
        }
        int leftH = getHeight(root.left);
        int rightH = getHeight(root.right);
        return leftH > rightH ? leftH + 1 : rightH + 1;
    }

    /**
     * O(N)
     *
     * @param root
     * @return
     */
    int maxDepth(TreeNode root) {
        if (root == null) {
            return 0;
        }
        int leftH = getHeight(root.left);
        int rightH = getHeight(root.right);
        if (leftH > 0 && rightH > 0 && Math.abs(leftH - rightH) <= 1) {
            return Math.abs(leftH - rightH) + 1;
        } else {
            return -1;
        }
    }

    // 检测值为value的元素是否存在
    TreeNode find(TreeNode root, int val) {
        if (root == null) {
            return null;
        }
        if (root.val == val) {
            return root;
        }
        TreeNode ret = find(root.left, val);
        if (ret.val == val) {
            return find(root.left, val);
        }
        ret = find(root.right, val);
        if (ret.val == val) {
            return find(root.right, val);
        }
        return null;
    }

    // 判断一棵树是不是完全二叉树
    boolean isCompleteTree(TreeNode root) {
        Queue<TreeNode> queue = new LinkedList<>();
        if (root != null) {
            queue.offer(root);
        }
        while (!queue.isEmpty()) {
            TreeNode cur = queue.peek();
            if (cur != null) {
                queue.offer(cur.left);
                queue.offer(cur.right);
            } else {
                break;
            }
        }
        while (!queue.isEmpty()) {
            TreeNode cur = queue.peek();
            if (cur != null) {
                return false;
            } else {
                queue.poll();
            }
        }
        return true;
    }

    // 层序遍历二叉树
    public void leveOrder(TreeNode root) {
        Queue<TreeNode> queue = new LinkedList<>();
        if (root != null) {
            queue.offer(root);
        }
        while (!queue.isEmpty()) {
            TreeNode cur = queue.poll();
            System.out.println(cur.val + " ");

            if (cur.left != null) {
                queue.offer(cur.left);
            }
            if (cur.right != null) {
                queue.offer(cur.right);
            }
        }
    }


    public List<List<TreeNode>> levelOrder(TreeNode root) {
        List<List<TreeNode>> ret = new ArrayList<>();
        if (ret == null) {
            return ret;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while (!queue.isEmpty()) {

            List<TreeNode> list = new ArrayList<>();
            int size = queue.size();
            while (size != 0) {
                TreeNode cur = queue.poll();
                list.add(cur);
                if (cur.left != null) {
                    queue.offer(cur.left);
                }
                if (cur.right != null) {
                    queue.offer(cur.right);
                }
                size--;
            }
            ret.add(list);
        }
        return ret;
    }

    /**
     * O(min(M,N)
     *
     * @param p
     * @param q
     * @return
     */
    //给你两棵二叉树的根节点 p 和 q ，编写一个函数来检验这两棵树是否相同
    public boolean isSameTree(TreeNode p, TreeNode q) {
        if (p != null && q == null || p == null && q != null) {
            return false;
        }
        if (p == null && q == null) {
            return true;
        }
        // p != null && q != null
        if (p.val != q.val) {
            return false;
        }
        return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
    }

    // 另一棵树的子树
    public boolean isSubtree(TreeNode root, TreeNode subRoot) {
        if (root == null || subRoot == null) {
            return false;
        }
        if (isSameTree(root, subRoot)) {
            return true;
        }
        if (isSubtree(root.left, subRoot)) {
            return true;
        }
        if (isSubtree(root.right, subRoot)) {
            return true;
        }
        return false;
    }
   /* public boolean isSameTree(TreeNode p, TreeNode q) {
        if(p != null && q == null  || p == null && q!= null) {
            return false;
        }
        if(p == null && q == null) {
            return true;
        }
        //p != null && q!= null
        if(p.val != q.val) {
            return false;
        }
        //p != null && q!= null  && p.val == q.val
        return isSameTree(p.left,q.left) && isSameTree(p.right,q.right);
    }
    */

    //判断一颗二叉树是否是平衡二叉树

    public boolean isBalanced(TreeNode root) {
        if (root == null) {
            return true;
        }
        int leftH = getHeight(root.left);
        int rightH = getHeight(root.right);
        return Math.abs(leftH - rightH) <= 1 && isBalanced(root.left) && isBalanced(root.right);

    }

    // 二叉树的最近公共祖先
    // 还可以使用两个链表求交点； 使用栈
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if (root == null) {
            return null;
        }
        if (root == p || root == q) {
            return root;
        }
        TreeNode leftTree = lowestCommonAncestor(root.left, p, q);
        TreeNode rightTree = lowestCommonAncestor(root.right, p, q);

        if (leftTree != null && rightTree != null) {
            return root;
        }

        if (leftTree != null) {
            return leftTree;
        }
        return rightTree;
    }


    //二叉树搜索树转换成排序双向链表
    public TreeNode Convert(TreeNode pRootOfTree) {
        if (pRootOfTree == null) {
            return null;
        }
        inOrder2(pRootOfTree);
        TreeNode head = pRootOfTree;
        if (head.left != null) {
            return null;
        }
        return head;
    }

    public TreeNode prev = null;

    void inOrder2(TreeNode root) {

        if (root == null) {
            return;
        }
        preOrder(root.left);
        root.left = prev;
        if (prev != null) {
            prev.right = root;
        }
        prev = root;
        preOrder(root.right);
    }

    //根据一棵树的前序遍历与中序遍历构造二叉树
    public int preIndex = 0;

    public TreeNode buildTree(int[] preorder, int[] inorder) {
        return buildTreeChild(preorder, inorder, 0, inorder.length - 1);
    }

    public TreeNode buildTreeChild(int[] preorder, int[] inorder, int inbegin, int inend) {

        if (inbegin > inend) {
            return null;//说明没有左树  或者 没有 右树了
        }

        TreeNode root = new TreeNode((char) preorder[preIndex]);

        int rootIndex = findIndex(inorder, preorder[preIndex], inbegin, inend);
        preIndex++;

        root.left = buildTreeChild(preorder, inorder, inbegin, rootIndex - 1);

        root.right = buildTreeChild(preorder, inorder, rootIndex + 1, inend);

        return root;
    }

    public int findIndex(int[] inorder, int key, int inbegin, int inend) {
        for (int i = inbegin; i <= inend; i++) {
            if (inorder[i] == key) {
                return i;
            }
        }
        return -1;
    }

    //根据二叉树创建字符串
    public String tree2str(TreeNode root) {
        StringBuilder sb = new StringBuilder();
        if (root == null) {
            return null;
        }
        tree2strChild(root, sb);
        return new String(sb);

    }

    public void tree2strChild(TreeNode t, StringBuilder sb) {
        if (t == null) {
            return;
        }
        sb.append(t.val);
        if (t.left != null) {
            sb.append("(");
            tree2strChild(t.left, sb);
            sb.append(")");
        } else {
            if (t.right == null) {
                return;
            } else {
                sb.append("()");
            }
        }
        if (t.right == null) {
            return;
        } else {
            sb.append(")");
            tree2strChild(t.right, sb);
            sb.append(")");
        }
    }


    // 二叉树前序非递归遍历实现
    public void preorderTraversal2(TreeNode root) {
        Stack<TreeNode> stack = new Stack<>();
        TreeNode cur = root;
        while (cur != null || !stack.empty()) {
            while (cur != null) {
                stack.push(cur);
                System.out.print(cur.val);
                cur = cur.left;
            }
            TreeNode top = stack.pop();
            cur = top.right;
        }
    }
    //二叉树中序非递归遍历实现
    public List<Integer> preorderTraversal4(TreeNode root) {
        List<Integer> list = new ArrayList<>();
        Stack<TreeNode> stack = new Stack<>();
        TreeNode cur = root;
        while (cur != null || !stack.empty()) {
            while (cur != null) {
                stack.push(cur);
                //System.out.print(cur.val + " ");
                //list.add(cur.val);
                cur = cur.left;
            }

            TreeNode top = stack.pop();
            cur = top.right;
        }
        return list;
    }


    //二叉树后序非递归遍历实现
    public List<Integer> postorderTraversal(TreeNode root) {
        List<Integer> list = new ArrayList<>();
        Stack<TreeNode> stack = new Stack<>();
        TreeNode cur = root;
        TreeNode prev = null;
        while (cur != null || !stack.empty()) {
            while (cur != null) {
                stack.push(cur);
                cur = cur.left;
            }
            TreeNode top = stack.peek();

            if (top.right == null || top.right == prev) {
                //list.add(top.val);
                prev = top;
                stack.pop();
            } else {
                cur = top.right;
            }

        }
        return list;
    }
}
